#include "Player.h"
#include <iostream>

Player::Player()
{
	moveLeft = false;
	moveRight = false;

	fire = false;
	shotTicks = 0;
	shotCooldown = 150;
	
}

Player::~Player()
{

}

bool Player::init(char *file, EntityType eT)
{
	if((entitySheet = Surface::load_image(file)) == NULL)
	{
		return false;
	}
	
	w = entitySheet->w;
	h = entitySheet->h;
	
	entType = eT;
	
	x = (WWIDTH - w) / 2;	
	y = WHEIGHT - (h + 10);

	return true;
}

void Player::input(SDL_Event *event)
{
	if(event -> type == SDL_KEYDOWN)
	{
		/* Movement */
		if(event -> key.keysym.sym == SDLK_LEFT)
		{
			moveLeft = true;
		}
		if(event -> key.keysym.sym == SDLK_RIGHT)
		{
			moveRight = true;
		}
		if(event -> key.keysym.sym == SDLK_SPACE)
		{
			std::cout << "test" << std::endl;
			fire = true;
		}	
		/* Other actions */
	}
	
	if(event -> type == SDL_KEYUP)
	{
		/* Movement */
		if(event -> key.keysym.sym == SDLK_LEFT)
		{
			moveLeft = false;
		}
		if(event -> key.keysym.sym == SDLK_RIGHT)
		{
			moveRight = false;
		}
		if(event -> key.keysym.sym == SDLK_SPACE)
		{
			fire = false;
		}	
	}
}

void Player::loop()
{
	/* ! Entity is not moving here */
	if(moveLeft == false && moveRight == false)
	{
		stop_move();
	}
	
	if(moveLeft == true)
	{
		xVel = -5.0f;
	}
	
	if(moveRight == true)
	{
		xVel = 5.0f;
	}
	
	move(xVel);
	create_bullet();
}

void Player::move(float moveX)
{
	if(moveX == 0)
	{
		return;
	}
	
	x += xVel * FPS::FPSControl.GetSpeedFactor();
	
	if(x < 10)
	{
		x = 10;
		xVel = -(xVel - xVel/4);
	}
	
	if(x > WWIDTH - w - 10)
	{
		x = WWIDTH - w - 10;
		xVel = -(xVel - xVel/4);
	}
}

void Player::stop_move()
{
	if(xVel == 0)
	{
		return;
	}
	
	if(xVel > 0.5f)
	{
		xVel -= 0.10f * FPS::FPSControl.GetSpeedFactor();
	}
	
	if(xVel < -0.5f)
	{
		xVel += 0.10f * FPS::FPSControl.GetSpeedFactor();
	}
	
	if(xVel >= -0.5f && xVel < 0)
	{
		xVel = 0;
	}
	
	if(xVel <= 0.5f && xVel > 0)
	{
		xVel = 0;
	} 
}

void Player::create_bullet()
{
	if(fire == true)
	{
		if(shotTicks + shotCooldown < SDL_GetTicks())
		{
			Bullet tmpBullet;
			tmpBullet.init("bullet.png");
			tmpBullet.x = (2 * x + tmpBullet.w) /2;
			tmpBullet.y = y;
					    
			bulletList.push_back(tmpBullet);

			shotTicks = SDL_GetTicks();
		}
	}
}